#!/usr/bin/env python
#coding: UTF-8

__author__="aaa"
__date__ ="2009-12-01"
import os
import time

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template

class Person(db.Model):
    name = db.StringProperty()
    birth = db.IntegerProperty()
    comment = db.StringProperty()

class MainPage(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'html/index.xhtml')
        self.response.out.write(template.render(path, {}))

class InputPerson(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'html/input.xhtml')
        self.response.out.write(template.render(path, {}))

class Insert(webapp.RequestHandler):
    def post(self):
        pname = self.request.get('name')
        pbirth = self.request.get('birth')
        pcomment = self.request.get('comment')
        Person(name=pname, birth=int(pbirth, 10), comment=pcomment).put()
        path = os.path.join(os.path.dirname(__file__), 'html/inputsuccess.xhtml')
        self.response.out.write(template.render(path, {}))

class Search(webapp.RequestHandler):
    def post(self):
        name = self.request.get('name')
        sosis = db.GqlQuery("SELECT * FROM Person WHERE name = :1", name)
        sosi = sosis.get()
        if sosi:
            now = time.localtime()
            age = now.tm_year - sosi.birth + 1
            comment = sosi.comment
        else:
            age = 0
            comment = "no comment"
        path = os.path.join(os.path.dirname(__file__), 'html/search.xhtml')
        template_values = {
            'age': age,
            'name': name,
            'comment': comment
        }
        self.response.out.write(template.render(path, template_values))

class ShowAllList(webapp.RequestHandler):
    def post(self):
        sosis = db.GqlQuery("SELECT * FROM Person")
        sosi = sosis.get()
        if sosi:
            now = time.localtime()
            age = now.tm_year - sosi.birth + 1
            comment = sosi.comment
        else:
            age = 0
            comment = "no comment"
        path = os.path.join(os.path.dirname(__file__), 'html/search.xhtml')
        template_values = {
            'age': age,
            'name': name,
            'comment': comment
        }
        self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication([
    ('/', MainPage),
    ('/input', InputPerson),
    ('/insert', Insert),
    ('/search', Search)
], debug=True)

def main():
#    db.delete(Person.all())
#    Person(name=unicode("佐藤", "UTF-8"), birth=1990).put()
#    Person(name="nakasima", birth=1991).put()
#    Person(name="9888", birth=1991).put()
#    Person(name="fumie", birth=1992).put()
#    Person(name="kawashima", birth=1993).put()
    run_wsgi_app(application)

if __name__ == "__main__":
    main()